import { login, getUserInfo } from '@/api/sys/sys'
// import md5 from 'md5'
import { setItem, getItem, removeAllItem } from '@/utils/storage/localStroage'
import { TOKEN, REFRESH_TOKEN } from '@/constant'
import { loginUser, userInfo, routerInfo, tokenObj } from '@/constant/interface/sys'
import router, { resetRouter } from '@/router'
import { toTree } from '@/utils/tree'
import { constRouter } from '@/router/routers'
import type { iBread } from '@/constant/interface/sys'

/**
 * 构建路由信息
 * @param menuList
 * @returns
 */
const initRouter = (menuList: any) => {
  const temp: any = []
  menuList.forEach(e => {
    if (e.path && /\S/.test(e.path)) {
      const r: routerInfo = {
        name: e.perms,
        path: e.path,
        component: null,
        meta: {
          id: e.id,
          title: e.name,
          // 填充面包屑信息
          breadList: breadCurmbInfo.get(e.id)
        }
      }
      try {
        r.component = () => import(`@/views${e.path}`)
      } catch (e) {
        console.log(e)
      }
      temp.push(r)
    }
  })
  return temp
}

const breadCurmbInfo = new Map()
/**
 * 构建面包屑
 * 循环数组拼接上级面包屑层级
 */
const initBreadCrumb = (treeList: any, parentName: Array<iBread>) => {
  treeList.forEach(element => {
    const breadList = [...parentName]
    const obj = {
      name: element.name,
      path: element.path
    }
    breadList.push(obj)
    breadCurmbInfo.set(element.id, breadList)
    if (element.children) {
      initBreadCrumb(element.children, breadList)
    }
  })
}

export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: {},
    menuTree: [],
    menuMap: new Map()
  }),
  getters: {
  },
  mutations: {
    setToken(state: any, token: tokenObj) {
      state.token = token.accessToken
      setItem(TOKEN, token.accessToken)
      setItem(REFRESH_TOKEN, token.refreshToken)
    },
    setUserInfo(state, userInfo: userInfo) {
      state.userInfo = userInfo
    },
    saveMenu(state, menuList: any) {
      const map = new Map()
      // todo 增加首页的菜单可以重新回到首页
      menuList = [{
        id: -1,
        name: '首页',
        path: '/home',
        icon: 'House'
      }, ...menuList]
      menuList.forEach(element => {
        element.title = element.name
        map.set(element.id, element)
      })
      state.menuMap = map
      state.menuTree = toTree([...menuList])
    }
  },
  actions: {
    /**
     * 登录
     * @param context
     * @param userInfo
     * @returns
     */
    async login(context: any, userInfo: loginUser) {
      const { username, password } = userInfo
      return await login({ username, password })
    },
    /**
     * 获取userInfo
     * @param param0
     * @returns
     */
    async getUserInfo({ dispatch, commit }) {
      const res = await getUserInfo()
      // 设置用户信息
      const { id, name, username, menuList } = res.data
      commit('setUserInfo', { id, name, username })
      // 设置用户权限
      await dispatch('generateMenus', menuList)
      return res
    },
    /**
     * 退出登录
     * @param param0
     */
    logout({ commit }) {
      commit('setToken', '')
      commit('setUserInfo', {})
      removeAllItem()
      // TODO: 清理权限
      router.push('/login')
    },
    /**
     * 认证用户的登录菜单 和 按钮权限
     * @param param0
     * @param menuList
     */
    generateMenus({ commit }, menuList: any) {
      // 构建页面左侧菜单层级
      commit('saveMenu', menuList)
      // 构建面包屑信息
      initBreadCrumb(toTree([...menuList]), [])
      // 初始化路由信息
      const accessRouters = initRouter(menuList)
      // accessRouters.push({ path: '/:pathMatch(.*)*', redirect: '/error/404', meta: { hideInMenu: true }})
      constRouter[0].children = (constRouter[0] as any).children.concat(accessRouters)
      accessRouters.push({ path: '/:pathMatch(.*)*', redirect: '/error/404', meta: { hideInMenu: true }})
      // 先重置路由
      resetRouter()
      // 添加动态路由
      router.addRoute(constRouter[0])
    }
  }
}
